
# create function to extract a tibble from the model output
# for one model at a time
create_latex_table_glm = function(mod_list = mod_list){
  resultz = list()
  i=1
  for(i in 1:length(mod_list)){
  
  CI = confint(mod_list[[i]])
  
  # extracting individual results into a table:
  mod1 <- mod_list[[i]]%>%
    broom.mixed::tidy(
      mod_list[[i]],
      effects = "fixed",        # <-- IMPORTANT: only convert fixed effects
      conf.int = TRUE,
      conf.method = "Wald"      # avoid profile CI errors
    ) %>%
    mutate(
      # Note: this might differ based on the model output:
      term=term,#for survival model: rownames(coef(summary(mod_list[[i]]))),
      # Note: for some results, we should not be using exp
      estimate_exp=round(exp(estimate), digits = 2),
      conf.int.low_exp=round(exp(conf.low), digits = 2), # missing values in mod 3 (check)
      conf.int.up_exp=round(exp(conf.high), digits = 2),
      model=i, 
      # extrac AIC (Note: would depend on the model)
      AIC = round(AIC(mod_list[[i]]), digits = 2),
      log_likelihood_value = as.numeric(sub(".*?(-?\\d+\\.\\d+).*", "\\1", round(logLik(mod_list[[i]]), digits = 2)))
    )%>%
    dplyr::select(term, estimate_exp, conf.int.low_exp, conf.int.up_exp, p.value, model, AIC, log_likelihood_value)%>%
    # removing any rows with p-values = NA because they are unlikely to have random effects or other indicators
    filter(!is.na(p.value))
  #mod1
  resultz[[i]] <- mod1
  
  } # closing an i-loop
  
  # binding all the results:
  mod_resultz <- do.call(rbind, lapply(resultz, as.data.frame))
  mod_resultz = mod_resultz %>%
    # removing oblasts as factors here
    filter(!grepl("^as\\.factor\\(ADM1_NAME", term))
  mod_resultz 
  # adding stars to the table:
  mod_resultz = mod_resultz%>%
    mutate(starz=case_when(
      p.value>=.1~'',
      p.value>=0.05&p.value<0.1~'^',
      p.value>=0.01&p.value<0.05~'*',
      p.value>=0.001&p.value<0.01~'**',
      p.value<0.001~'***'
    )
    )%>%
    mutate(ESTIMATE=paste0(estimate_exp, starz))%>%
    mutate(est_conf_int=paste0(ESTIMATE, '(', conf.int.low_exp, '; ', conf.int.up_exp, ')'))%>%
    dplyr::select(term, est_conf_int, AIC, log_likelihood_value, model)
  mod_resultz 
  
  # AIC:
  aic_tab = mod_resultz %>%
    dplyr::select(AIC, model)%>%
    filter(!duplicated(model))%>%
    mutate(ID = seq(1, length(model), by = 1))
  # NOTE: save this as tibble; otherwise spread is not going to work.
  aic_tab = as_tibble(aic_tab)
  aic_tab = spread(aic_tab, 'model', 'AIC')
  aic_tab = sapply(aic_tab, function(x) x[!is.na(x)])
  aic_tab = do.call(cbind, aic_tab)
  aic_tab = as.data.frame(aic_tab)
  aic_tab = aic_tab[1,]
  aic_tab; class(aic_tab)
  aic_tab = aic_tab %>%  
    dplyr::rename(term=ID)%>%
    mutate(term='AIC')
  aic_tab
  
  
  # log_lik tab:
  ll_tab = mod_resultz %>%
    dplyr::select(log_likelihood_value, model)%>%
    filter(!duplicated(model))%>%
    mutate(ID = seq(1, length(model), by = 1))
  # NOTE: save this as tibble; otherwise spread is not going to work.
  ll_tab = as_tibble(ll_tab)
  ll_tab = spread(ll_tab, 'model', 'log_likelihood_value')
  ll_tab = sapply(ll_tab, function(x) x[!is.na(x)])
  ll_tab = do.call(cbind, ll_tab)
  ll_tab = as.data.frame(ll_tab)
  ll_tab = ll_tab[1,]
  ll_tab; class(ll_tab)
  ll_tab = ll_tab %>%  
    dplyr::rename(term=ID)%>%
    mutate(term='log_likelihood_value')
  ll_tab
  
  

  ##########################
  mod_resultz2 = mod_resultz %>%
    dplyr::select(-AIC, -log_likelihood_value)
  mod_resultz2
  
  # from long to wide:
  library(reshape2)
  reshape2::melt(mod_resultz2, id.vars=c('est_conf_int'))
  mod_res_wide = spread(mod_resultz2, 'model', 'est_conf_int') # est_conf_int
  mod_res_wide
  mod_res_wide = mod_res_wide %>%
    mutate(term = case_when(
       term == 'disruption_intentional_3indicators_1dlag'~'Internet Outage (R) (lag)', 
      #term == 'hr_abuse_reported_1dlag'~'Human Rights Abuse (lag)',
      term == 'as.factor(war_phases_1dlag)Rus Maneuver Defensive' ~ 'Rus Defensive Maneuver (lag)',
      term == 'as.factor(war_phases_1dlag)Rus Maneuver Offensive' ~ 'Rus Offensive Maneuver I(lag)', 
      term == 'as.factor(territorial_control_80_1dlag)Ukrainian control' ~ 'Rus Punishment in Ukr Territories(lag)',
      term == 'territorial_control_80_1dlagContested' ~ 'Contested (lag)',
      term == 'log_rus_mil_t_1dlag_sc'~'Kinetic (R) (lag,log,sc)',
      term == 'log_ukr_mil_1dlag_sc'~'Kinetic (U) (lag,log,sc)',
      term == 'log_rus_mil_t_1dlag'~'Rus Kinetic (lag,log)',
      term == 'holiday_dummy'~'Holidays',
      term == 'as.factor(WEEKEND)1'~'Weekend',
      term == '(Intercept)' ~ '(Intercept)',
      # for ukr model: 
      term == 'disruption_unintentional_3indicators_1dlag'~'Internet Outage (U) (lag)', 
      term == 'as.factor(war_phases_ukr)Offensive Maneuver (U)' ~ 'Offensive Maneuver (U)',
      term == 'as.factor(war_phases_ukr)Defensive Maneuver (U)' ~ 'Defensive Maneuver (U)',
      term == 'territorial_control_80_1dlagRussian occupation' ~ 'Territorial Control (R) (lag)',
      term == 'log_ukr_mil_t_1dlag'~'Kinetic (U) (lag,log)'      
     )
    )%>%
    # match is working, factor and levels are not working for some reaons
    dplyr::arrange(match(term, c(
      'Offensive Maneuver (R)', 'Defensive Maneuver (R)',
      'Offensive Maneuver (U)', 'Defensive Maneuver (U)',
      'Contested (lag)', 'Territorial Control (U) (lag)', 'Territorial Control (R) (lag)',
      'Kinetic (R) (lag,log)', 'Kinetic (U) (lag,log)', 
      'Kinetic (R+U) (lag,log)',
      'Human Rights Abuse (lag)',
      'Holidays', 'Weekend',
      # intercept:
      '(Intercept)',
      # lag
      'Internet Outages (R) (lag)',
      'Internet Outages (U) (lag)'
    ))
    )%>%
    replace(is.na(.), '------')
  mod_res_wide
  
  # merging concordate with the rest of the results
  rez_all = mod_res_wide %>%
    rbind(aic_tab) %>%
    rbind(ll_tab)
  rez_all
  dim(rez_all)
  library(xtable)
  xtable(rez_all)
  
} # function closes
